package com.example.websocket.dto;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

@Slf4j
@Getter
@Setter
public class WSMultipleSessionDataDTO {
    protected String uniqueCode;
    protected Map<String,WebSocketSession> sessions = new HashMap<>();

    public WSMultipleSessionDataDTO(WebSocketSession session, String uniqueCode) {
        this.uniqueCode = uniqueCode;
        addSession(session);
    }

    public boolean equalsUniqueCode(String uniqueCode) {
        return StringUtils.equals(uniqueCode,this.uniqueCode);
    }

    public void addSession(WebSocketSession session) {
       this.sessions.put(session.getId(),session);
    }

    public void removeSession(WebSocketSession session) {
        try {
            session.close();
        } catch (IOException e) {
            log.error("",e);
        }
        this.sessions.remove(session.getId());
    }

    public synchronized void sendMessage(WebSocketMessage<?> message) {
        Set<WebSocketSession> closed = new HashSet<>();
        for (WebSocketSession ele : sessions.values()) {
            try {
                if (ele.isOpen()) {
                    ele.sendMessage(message);
                }else {
                    closed.add(ele);
                }
            } catch (IOException e) {
                log.error("发送信息异常",e);
            }
        }
         if (!closed.isEmpty()) {
             closed.forEach(this::removeSession);
         }
    }
    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        WSMultipleSessionDataDTO student = (WSMultipleSessionDataDTO) o;
        return StringUtils.equals(uniqueCode,student.uniqueCode);
    }

    @Override
    public int hashCode() {
        int result = 17;
        return 31 * result + uniqueCode.hashCode();
    }
}
